
require 'uuidtools'

class UUIDHelper
  
  NICTA_NAMESPACE = UUID.parse("1b6c993f-616e-4476-bd06-8aa50a1b698f")

  @@namespaces = {}
  
  def self.namespace(name)
    @@namespaces[name] ||= UUID.sha1_create(NICTA_NAMESPACE, name)
  end

  def self.create(namespace, name)
    ns = namespace(name)
    UUID.sha1_create(ns, name).to_s
  end
 
  def self.create22(namespace, name)
    ns = namespace(name)
    UUID.sha1_create(ns, name).to_s22
  end
  
  # Create a hash by turning each element of 'value_array' into
  # a hash entry with the element being the value and the key
  # being a uuid created from the 'namespace' and the value. If
  # the elements in 'value_array' are 2D arrays, then the first
  # index is used to create the UUID, while the second one is
  # used for the hash value
  #
  # Note, the uuid created should always be the same for the same
  # value and namespace.
  #
  def self.create_hash(namespace, value_array)
    ns = namespace(namespace)
    h = {}
    value_array.each do |e|
      if e.kind_of? Array
        h[UUID.sha1_create(ns, e[1]).to_s] = e[0]
      else
        h[UUID.sha1_create(ns, e).to_s] = e
      end
    end
    h
  end
  
  # Create a new array by turning each element of 'value_array' into
  # a 2D array with the element being the first and the second being 
  # a uuid created from the element and the 'namespace'.
  #
  # Note, the uuid created should always be the same for the same
  # value and namespace.
  #
  def self.create_array(namespace, value_array)
    ns = namespace(namespace)
    a = []
    value_array.each do |e|
      a << [UUID.sha1_create(ns, e).to_s, e]
    end
    a
  end
  
  def self.hash_to_array(hash)
    a = []
    hash.each do |k, v|
      a << [v, k]
    end
    a.sort
  end 
 
end



#--
# Copyright (c) 2007 Maximilian Ott
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#++
